<template>
    <div class="user-add">
        <el-form :model="eleForm" :rules="rules" label-width="95px" size="medium" ref="eleForm" @keyup.enter.native="onSubmit">
            <el-form-item label="账号" prop="accunt">
                <el-input v-model.trim="eleForm.accunt" style="width:200px" placeholder="请输入账号"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model.trim="eleForm.password" type="password" style="width:200px" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item label="角色">
                <el-select v-model="eleForm.identity" placeholder="请选择" clearable>
                    <el-option :label="item.name" :value="item.value" v-for="item in opt_identity" :key="item.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用户名">
                <el-input v-model.trim="eleForm.username" style="width:200px" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="余额" v-if="user.identity === 'admin'">
                <el-input v-model.trim="eleForm.money" type="number" style="width:399px" placeholder="请输入余额"></el-input>
            </el-form-item>
            <el-form-item label="地址">
                <el-input v-model.trim="eleForm.address" style="width:399px" placeholder="请输入地址"></el-input>
            </el-form-item>
        </el-form>
        <div class="img">
            <div class="imgUrl">
                <img :src="eleForm.avator" v-if="eleForm.avator" alt="">
                <div class="oper" v-if="eleForm.avator">
                    <i class="el-icon-zoom-in" @click="showBigImage(eleForm.avator)"></i>
                </div>
            </div>
            <el-upload class="user-img-upload" :action="imgUrl" :headers="getHeaders()" :show-file-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess" name="userImg">
                <el-button type="primary">上传照片</el-button>
            </el-upload>
        </div>
        <div style="text-align:center">
            <el-button @click="escClick">取消</el-button>
            <el-button type="primary" @click="onSubmit" :loading="submitLoading">提交</el-button>
        </div>
    </div>
</template>
<script>
// 发请求全部导入
import api from '@/api/user/index'
// 工具
import tool from '@/utils/tool'
export default {
    props:['dialogInfo'],
    data() {
        return {
            // 提交时避免重复点击
            submitLoading:false,
            // 角色
            opt_identity:tool.identity,
            // 上传照片地址
            imgUrl:this.$url.userImageUpload,
            // 图片放大
            // 接受的数组
            viewUrl:[],

            eleForm:{
                accunt:'',
                password:'',
                username:'',
                identity:'',
                money:'',
                address:'',
                avator:''
            },
            rules:{
                accunt:[
                    {required:true,message:'请输入账号',trigger:'blur'},
                    {min:4,max:30,message:'长度在4到30个字符之间',trigger:'blur'}
                ],
                password:[
                    {required:true,message:'请输入密码',trigger:'blur'},
                    {min:4,max:30,message:'长度在4到30个字符之间',trigger:'blur'}
                ],
            },
        }
    },
    computed: {
        user(){
            return this.$store.getters.user
        },
    },
    methods: {
        // 取消
        escClick(){
            this.$emit('dialogCancel')
        },
        // 提交
        onSubmit(){
            // 更新
            if(this.dialogInfo){
                this.$refs.eleForm.validate(valid=>{
                    if(!valid) return
                    console.log(this.eleForm)
                    this.submitLoading = true
                    api.updateUser(this.eleForm).then(res=>{
                        this.submitLoading = false
                        if(res.code !==200 ) return
                        console.log(res)
                        this.$message.success('更新成功!')
                        this.$emit('dialogSubmit')
                    })
                })
            // 新增
            }else{
                this.$refs.eleForm.validate(valid=>{
                    if(!valid) return
                    console.log(this.eleForm)
                    this.submitLoading = true
                    api.addUser(this.eleForm).then(res=>{
                        this.submitLoading = false
                        if(res.code !==200 ) return
                        console.log(res)
                        this.$message.success('添加成功!')
                        this.$emit('dialogSubmit')
                    })
                })
            }
        },
        // 加token
        getHeaders(){
            var headers = {}
            headers["tokenKey"] = window.localStorage.getItem("tokenKey")
            return headers;
        },
        // 上传之前
        handleBeforeUpload(file){
            let isRightType = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/tiff' || file.type === 'image/bmp'||file.type === 'image/jpg';
            let is5M = file.size / 1024 / 1024 < 5;
            if (!isRightType) {
                this.$message.warning('上传图片只能是 JPG JPEG TIFF BMP PNG 格式!');
                return false
            }
            if (!is5M) {
                this.$message.warning('上传图片大小不能超过 5MB!');
                return false
            }
            return isRightType && is5M;
        },
        // 上传成功(这些参数fileList包含file包含res)
        handleSuccess(res,file,fileList){
            // 文件上传没有使用axios，这里的自己处理
            // 失效的时候，先清除，再去登录页
            if(res.code === 598){
                this.$message.warning(res.msg)
                localStorage.removeItem('tokenKey')
                localStorage.removeItem('by_menu')
                location.href = '/login'
            }

            if(res.code!==200) return
            this.eleForm.avator = res.data.filename
        },
        // 放大图片
        showBigImage(url){
            this.viewUrl = []
            this.viewUrl.push(url)
            window.createPreview(this.viewUrl)
        }
    },
    created() {
        console.log(this.dialogInfo)
        if(this.dialogInfo){
            // 如果有,那就是更新操作(执行深拷贝，不然会影响父组件的数据------对象的传递传递的是引用)
            this.eleForm = JSON.parse(JSON.stringify(this.dialogInfo))
            // 这里得去掉密码，因为是加密过来的码，没有用
            this.eleForm.password = ''
            // 处理角色
            this.eleForm.identity = this.eleForm.identity ? tool.getValueByName(tool.identity,this.eleForm.identity) : ''
        }
    },
    mounted() {
    },
}
</script>
<style lang="less" scoped>
.user-add{
    position: relative;
}
.user-add .img{
    width: 160px;
    height: 210px;
    position: absolute;
    top: 0px;
    right: 56px;
}
.user-add .img .imgUrl{
    position: relative;
    width: 160px;
    height: 170px;
    overflow: hidden;
    box-sizing: border-box;
    border: 1px solid #efefef;
    background: url(../../assets/img/faceBg.png) no-repeat center center;
}
.user-add .img .imgUrl img{
    box-sizing: border-box;
    display: block;
    width: 100%;
    height: 100%;
}
.user-add .img .imgUrl .oper{
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    transition: all 0.3s ease;
    text-align: center;
    color: #fff;
    background-color: rgba(0, 0, 0, .5);
    padding-top: 80px;
    opacity: 0;
    cursor: pointer;
}
.user-add .img .imgUrl .oper:hover{
    opacity: 1;
}
.user-add .img .user-img-upload{
    position: absolute;
    bottom: 0px;
    left: 50%;
    transform: translateX(-50%);
    height: 30px;
    overflow: hidden;
}
.user-add .img .user-img-upload /deep/ .el-button--primary{
    height: 30px;
    padding: 0px;
    line-height: 30px;
    width: 160px;
}
// el-select样式重写
.el-select{
    width: 200px !important;
}
</style>